package transaction.mq.order.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import transaction.mq.order.mapper.XcTaskHisMapper;
import transaction.mq.order.mapper.XcTaskMapper;
import transaction.mq.order.model.XcTask;
import transaction.mq.order.model.XcTaskHis;

import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 **/
@Service
public class TaskService {

    @Autowired
    XcTaskMapper xcTaskMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    XcTaskHisMapper xcTaskHisMapper;

    //查询前n条任务
    public List<XcTask> findXcTaskList(Date updateTime, int size) {
        //设置分页参数
        PageHelper.startPage(0, size);
        // 查询
        Example example = new Example(XcTask.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("updateTime", updateTime);
        //查询前n条任务
        PageInfo<XcTask> pageinfo = new PageInfo<>(xcTaskMapper.selectByExample(example));
        List<XcTask> list = pageinfo.getList();
        return list;
    }

    //发布消息
    public void publish(XcTask xcTask, String ex, String routingKey) {
        XcTask optional = xcTaskMapper.selectByPrimaryKey(xcTask.getId());
        if (optional != null) {
            rabbitTemplate.convertAndSend(ex, routingKey, xcTask);
            //更新任务时间
            optional.setUpdateTime(new Date());
            xcTaskMapper.updateByPrimaryKeySelective(optional);
        }
    }

    //获取任务
    public int getTask(String id, int version) {
        //通过乐观锁的方式来更新数据表，如果结果大于0说明取到任务
        int count = xcTaskMapper.updateTaskVersion(id, version);
        return count;
    }

    //完成任务
    @Transactional(rollbackFor = Exception.class)
    public void finishTask(String taskId) {
        XcTask optionalXcTask = xcTaskMapper.selectByPrimaryKey(taskId);
        if (optionalXcTask != null) {
            //历史任务
            XcTaskHis xcTaskHis = new XcTaskHis();
            BeanUtils.copyProperties(optionalXcTask, xcTaskHis);
            xcTaskHisMapper.insertSelective(xcTaskHis);
            xcTaskMapper.deleteByPrimaryKey(optionalXcTask.getId());
        }
    }
}
